local skynet = require "skynet"
local cluster = require "cluster"

require "skynet.manager"	-- import skynet.register

local configdb = {}
local command = {}
local configserver = nil


function printtable(t)
   for key,value in pairs(t) do
     if type(value) == "table" then
          for key2,value2 in pairs(value) do
              skynet.error("key="..key2.." value="..value2)
          end
      end
    end
end

function comparetable(t1,t2)
   for key,value in pairs(t1) do
     if type(value) == "table" then
          for key2,value2 in pairs(value) do
              skynet.error("key="..key2.." value="..value2)
          end
      end
    end
end


function command.GET(key)
	local l = configdb[tostring(key)]
	if l == nil then
		skynet.error("configdb not find the key:"..tostring(key))
		return nil
	end
	skynet.error("command.GET = "..key.." "..l[1].." "..l[2])
	return configdb[tostring(key)]
end

function request_config() 
	skynet.error("request_config start")
    skynet.fork(function() 
    	while true do
	    if configserver then
	    	local configdbbak = configdb
	        configdb = configserver.req.getconfig("name","gateconfig")

	        --skynet.error("request_config succeed ")
            --printtable(configdb)
	    end
	    skynet.sleep(300)
		end
	end)
end

skynet.start(function()
	skynet.error("start configdb server")
	skynet.dispatch("lua", function(session, address, cmd, ...)
		cmd = cmd:upper()
		local f = command[cmd]
		if f then
			skynet.ret(skynet.pack(f(...)))
		else
			error(string.format("Unknown command %s", tostring(cmd)))
		end
	end)

	skynet.register ".configdb"
	configserver = cluster.snax("master", "gateconfigser")
	request_config()

	skynet.error("configdb self = "..skynet.self())
end)
